package com.android.manghe.mine.activity;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;

import com.android.base.frame.view.MVPActivity;
import com.android.base.tools.MediaUtil;
import com.android.base.tools.ToastUtil;
import com.android.base.tools.permission.OnPermissionResultListener;
import com.android.base.tools.permission.PermissionUtil;
import com.android.manghe.R;
import com.android.manghe.mine.presenter.PUnderAge;
import com.android.manghe.view.crop.ImageCropHelper;
import com.android.manghe.view.multiselectorview.MultiImageSelectorView;
import com.isseiaoki.simplecropview.CropImageView;
import com.yanzhenjie.permission.runtime.Permission;

import java.util.ArrayList;
import java.util.List;

import me.nereo.multi_image_selector.MultiImageSelector;
import me.nereo.multi_image_selector.MultiImageSelectorActivity;

/**
 * author : liuwen
 * e-mail : liuwen370494581@163.com
 * time   : 2021/12/28 13:41
 * desc   :未年成保护
 */
public class UnderAgeActivity extends MVPActivity<PUnderAge> {

    private EditText mEtName, mEtPhone, mEtCard, mEtContent;
    private MultiImageSelectorView mImageSelectorViewOne, mImageSelectorViewTwo, mImageSelectorViewThree;
    private RelativeLayout mLayoutPicTipOne, mLayoutPicTipTwo, mLayoutPicTipThree;
    private TextView mTvCountTip, mTvSure;

    private int CODE_IMAGE_SELECT_ONE = 100;
    private int CODE_IMAGE_CROP_ONE = 101;

    private int CODE_IMAGE_SELECT_TWO = 103;
    private int CODE_IMAGE_CROP_TWO = 104;

    private int CODE_IMAGE_SELECT_THREE = 105;
    private int CODE_IMAGE_CROP_THREE = 106;

    @Override
    protected void initData(@Nullable Bundle savedInstanceState) {
        getTitleBar().setToolbar("未年成保护").setLeftIcon(R.mipmap.icon_back_black).hideBottomLine()
                .setRightText("反馈记录", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        open(UnderAgeFeedBackActivity.class);
                    }
                })
                .setBackgroundColor(ContextCompat.getColor(mContext, R.color.white));

        mEtCard = findViewById(R.id.id_ed_card);
        mEtName = findViewById(R.id.id_ed_name);
        mEtPhone = findViewById(R.id.id_ed_phone);
        mEtContent = findViewById(R.id.etContent);
        mTvCountTip = findViewById(R.id.fontCountTip);
        mTvSure = findViewById(R.id.id_tv_sure);

        mImageSelectorViewOne = findViewById(R.id.multiImageSelectorView_1);
        mImageSelectorViewTwo = findViewById(R.id.multiImageSelectorView_2);
        mImageSelectorViewThree = findViewById(R.id.multiImageSelectorView_3);

        mLayoutPicTipOne = findViewById(R.id.layoutPicTip_1);
        mLayoutPicTipTwo = findViewById(R.id.layoutPicTip_2);
        mLayoutPicTipThree = findViewById(R.id.layoutPicTip_3);

        mImageSelectorViewOne.setShowAddImageOnMaximum(false);
        mImageSelectorViewTwo.setShowAddImageOnMaximum(false);
        mImageSelectorViewThree.setShowAddImageOnMaximum(false);

        mImageSelectorViewOne.setImageMaxCount(2);
        mImageSelectorViewTwo.setImageMaxCount(1);
        mImageSelectorViewThree.setImageMaxCount(1);

        initListener();

    }

    public void submitOk(String text) {
        ToastUtil.showShort(this, text);
        finish();
    }

    public void submitFail(String text) {
        ToastUtil.showShort(this, text == null ? "提交失败" : text);
    }

    private void initListener() {

        mLayoutPicTipOne.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                PermissionUtil.requestPermissions(
                        mContext, new OnPermissionResultListener() {
                            @Override
                            public void onGranted(List<String> permissions) {
                                multiImageSelector(getP().getPicLocalPathListOne(), CODE_IMAGE_SELECT_ONE);
                            }
                        },
                        Permission.WRITE_EXTERNAL_STORAGE, Permission.CAMERA);
            }
        });


        mLayoutPicTipTwo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                PermissionUtil.requestPermissions(
                        mContext, new OnPermissionResultListener() {
                            @Override
                            public void onGranted(List<String> permissions) {
                                multiImageSelector(getP().getPicLocalPathListTwo(), CODE_IMAGE_SELECT_TWO);
                            }
                        },
                        Permission.WRITE_EXTERNAL_STORAGE, Permission.CAMERA);
            }
        });

        mLayoutPicTipThree.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                PermissionUtil.requestPermissions(
                        mContext, new OnPermissionResultListener() {
                            @Override
                            public void onGranted(List<String> permissions) {
                                multiImageSelector(getP().getPicLocalPathListThree(), CODE_IMAGE_SELECT_THREE);
                            }
                        },
                        Permission.WRITE_EXTERNAL_STORAGE, Permission.CAMERA);
            }
        });
        mImageSelectorViewOne.setOnItemClickListener(new MultiImageSelectorView.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {

            }

            @Override
            public void onDelete(View view, int position) {
                if (position >= 0 && position < getP().getPicLocalPathListOne().size()) {
                    getP().getPicLocalPathListOne().remove(position);
                    mImageSelectorViewOne.setList(getP().getPicLocalPathListOne());
                    sureNext();
                }
            }

            @Override
            public void onAdd(View view) {
                PermissionUtil.requestPermissions(
                        mContext, new OnPermissionResultListener() {
                            @Override
                            public void onGranted(List<String> permissions) {
                                multiImageSelector(getP().getPicLocalPathListOne(), CODE_IMAGE_SELECT_ONE);
                            }
                        },
                        Permission.WRITE_EXTERNAL_STORAGE, Permission.CAMERA);
            }

            @Override
            public void onReachTheMaximum() {

            }
        });

        mImageSelectorViewTwo.setOnItemClickListener(new MultiImageSelectorView.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {

            }

            @Override
            public void onDelete(View view, int position) {
                if (position >= 0 && position < getP().getPicLocalPathListTwo().size()) {
                    getP().getPicLocalPathListTwo().remove(position);
                    mImageSelectorViewTwo.setList(getP().getPicLocalPathListTwo());
                    sureNext();
                }
            }

            @Override
            public void onAdd(View view) {
                PermissionUtil.requestPermissions(
                        mContext, new OnPermissionResultListener() {
                            @Override
                            public void onGranted(List<String> permissions) {
                                multiImageSelector(getP().getPicLocalPathListTwo(), CODE_IMAGE_SELECT_TWO);
                            }
                        },
                        Permission.WRITE_EXTERNAL_STORAGE, Permission.CAMERA);
            }

            @Override
            public void onReachTheMaximum() {

            }
        });

        mImageSelectorViewThree.setOnItemClickListener(new MultiImageSelectorView.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {

            }

            @Override
            public void onDelete(View view, int position) {
                if (position >= 0 && position < getP().getPicLocalPathListThree().size()) {
                    getP().getPicLocalPathListThree().remove(position);
                    mImageSelectorViewThree.setList(getP().getPicLocalPathListThree());
                    sureNext();
                }
            }

            @Override
            public void onAdd(View view) {
                PermissionUtil.requestPermissions(
                        mContext, new OnPermissionResultListener() {
                            @Override
                            public void onGranted(List<String> permissions) {
                                multiImageSelector(getP().getPicLocalPathListThree(), CODE_IMAGE_SELECT_THREE);
                            }
                        },
                        Permission.WRITE_EXTERNAL_STORAGE, Permission.CAMERA);
            }

            @Override
            public void onReachTheMaximum() {

            }
        });

        mEtName.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                sureNext();
            }
        });

        mEtCard.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                sureNext();
            }
        });

        mEtPhone.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                sureNext();
            }
        });

        mEtContent.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @SuppressLint("SetTextI18n")
            @Override
            public void afterTextChanged(Editable s) {
                mTvCountTip.setText(mEtContent.getText().toString().length() + "/200");
                sureNext();
            }
        });

        mTvSure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String phone = mEtPhone.getText().toString().trim().intern();
                String card = mEtCard.getText().toString().trim().intern();
                String name = mEtName.getText().toString().trim().intern();
                String content = mEtContent.getText().toString().trim().intern();
                getP().submit(name, card, phone, content);
            }
        });
    }

    private void sureNext() {
        String phone = mEtPhone.getText().toString().trim().intern();
        String card = mEtCard.getText().toString().trim().intern();
        String name = mEtName.getText().toString().trim().intern();
        String content = mEtContent.getText().toString().trim().intern();

        if (!TextUtils.isEmpty(phone)
                && !TextUtils.isEmpty(card)
                && !TextUtils.isEmpty(name)
                && !TextUtils.isEmpty(content)
                && (getP().getPicLocalPathListOne().size() > 0
                || getP().getPicLocalPathListTwo().size() > 0
                || getP().getPicLocalPathListThree().size() > 0)) {

            mTvSure.setBackgroundResource(R.drawable.btn_gradient_shape);
            mTvSure.setTextColor(ContextCompat.getColor(mContext, R.color.colorFont33));
            mTvSure.setEnabled(true);
        } else {
            mTvSure.setBackgroundResource(R.drawable.btn_disable_round_selector);
            mTvSure.setTextColor(ContextCompat.getColor(mContext, R.color.white));
            mTvSure.setEnabled(false);
        }
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_under_age;
    }


    private void multiImageSelector(ArrayList<String> imgs, int code) {
        MultiImageSelector.create()
                .showCamera(true) // show camera or not. true by default
                .count(3) // max select image size, 9 by default. used width #.multi()
                .single() // multi mode, default mode;
                .origin(imgs) // original select data set, used width #.multi()
                .start(this, code);
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == CODE_IMAGE_SELECT_ONE) {
                theSameCode(data, CODE_IMAGE_CROP_ONE);
            } else if (requestCode == CODE_IMAGE_SELECT_TWO) {
                theSameCode(data, CODE_IMAGE_CROP_TWO);
            } else if (requestCode == CODE_IMAGE_SELECT_THREE) {
                theSameCode(data, CODE_IMAGE_CROP_THREE);
            } else if (requestCode == CODE_IMAGE_CROP_ONE) {
                Uri resultUri = ImageCropHelper.onActivityResult(resultCode, data);
                if (resultUri != null) {
                    String imagePath = MediaUtil.getPath(this, resultUri);
                    getP().getPicLocalPathListOne().add(imagePath);
                    mLayoutPicTipOne.setVisibility(View.GONE);
                    mImageSelectorViewOne.setVisibility(View.VISIBLE);
                    mImageSelectorViewOne.setList(getP().getPicLocalPathListOne());
                    sureNext();
                }
            } else if (requestCode == CODE_IMAGE_CROP_TWO) {
                Uri resultUri = ImageCropHelper.onActivityResult(resultCode, data);
                if (resultUri != null) {
                    String imagePath = MediaUtil.getPath(this, resultUri);
                    getP().getPicLocalPathListTwo().add(imagePath);
                    mLayoutPicTipTwo.setVisibility(View.GONE);
                    mImageSelectorViewTwo.setVisibility(View.VISIBLE);
                    mImageSelectorViewTwo.setList(getP().getPicLocalPathListTwo());
                    sureNext();
                }
            } else if (requestCode == CODE_IMAGE_CROP_THREE) {
                Uri resultUri = ImageCropHelper.onActivityResult(resultCode, data);
                if (resultUri != null) {
                    String imagePath = MediaUtil.getPath(this, resultUri);
                    getP().getPicLocalPathListThree().add(imagePath);
                    mLayoutPicTipThree.setVisibility(View.GONE);
                    mImageSelectorViewThree.setVisibility(View.VISIBLE);
                    mImageSelectorViewThree.setList(getP().getPicLocalPathListThree());
                    sureNext();
                }
            }
        }
    }

    private void theSameCode(Intent data, int code) {
        if (data != null) {
            List<String> arrayList = data.getStringArrayListExtra(MultiImageSelectorActivity.EXTRA_RESULT);
            if (arrayList != null && !arrayList.isEmpty()) {
                ImageCropHelper.startCropFree(this, arrayList.get(0),
                        ImageCropHelper.ImageCropParamsBuilder
                                .create()
                                .compressQuality(90)
                                .cropMode(CropImageView.CropMode.FREE)
                                .outputMaxSize(1280, 1280)
                                .build(), code);
            }
        }
    }
}
